package com.hcb.tonguetiphealth.widget.drinksbook;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.DrinksBookListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.manager.ListComparatorManager;
import com.hcb.tonguetiphealth.model.Drinks;
import com.hcb.tonguetiphealth.model.Wine;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class DrinksBookWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "DrinksBookWidget";
	private String url = Global.URL + Global.servlet_wines;
	
	private Activity ctx;
	private Handler mHandler;
	private Button brand, price, type, popularity;
	private LinearLayout back, cart;
	private ListView drinksListView;
	private View footerView;
	private TextView tv_footerMore;
	private ProgressBar pb_footerMore;
	private List<Drinks> drinksList;
	private DrinksBookListAdapter drinksAdapter;
	private DrinksBookDialog drinksBookDialog;
	private Wine wine;
	private Wine wineBrand;
	private Wine wineType;
	private Wine winePrice;
	private String wineBrandName;
	private String wineTypeId;
	private String wineLowPrice;
	private String wineHighPrice;
	private int mCount = 0;
	private boolean reSet = false;
	private PopupWindow popupWindow;
	
//	@SuppressLint("HandlerLeak")
	public DrinksBookWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.drinks_book, this); 
		footerView = LayoutInflater.from(context).inflate(R.layout.refresh_list_footer, null); 
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在获取酒水列表...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					reSet = false;
					tv_footerMore.setText(R.string.app_list_footer_more_text);
					pb_footerMore.setVisibility(ProgressBar.GONE);
					
					drinksAdapter.notifyDataSetChanged();
					dismissMessageDialog();
					break;
				case Wine.TYPE:
					reSet = true;
					wine = (Wine)msg.obj;
					wineType.setStrId(wine.getStrId());
					wineType.setName(wine.getName());
					wineBrand.setStrId("-1");
					winePrice.setStrId("-1");
					brand.setText("品牌");
					price.setText("价格");
					popularity.setText("人气");
					if(wine.getStrId().equals("-1")) {
						type.setText("类型");
					} else {
						type.setText(wine.getName());
					}
					initData();
					//screenDrinks(msg.what, wine);
					break;
				case Wine.BRAND:
					reSet = true;
					wine = (Wine)msg.obj;
					wineBrand.setStrId(wine.getStrId());
					wineBrand.setName(wine.getName());
					winePrice.setStrId("-1");
					price.setText("价格");
					popularity.setText("人气");
					if(wine.getStrId().equals("-1")) {
						brand.setText("品牌");
					} else {
						brand.setText(wine.getName());
					}
					initData();
					//screenDrinks(msg.what, wine);
					break;
				case Wine.PRICE:
					reSet = true;
					wine = (Wine)msg.obj;
					winePrice.setStrId(wine.getStrId());
					winePrice.setName(wine.getName());
					popularity.setText("人气");
					if(wine.getStrId().equals("-1")) {
						price.setText("价格");
					} else {
						price.setText(wine.getName());
					}
					initData();
					//screenDrinks(msg.what, wine);
					break;
				case Wine.POPULARITY:
					wine = (Wine)msg.obj;
					popularity.setText(wine.getName());
					compareDrinksList(StringUtils.parseInt(wine.getStrId()));
					break;
				}
			}
		};
		wineBrand = new Wine();
		wineType = new Wine();
		winePrice = new Wine();
		
		tv_footerMore = (TextView)footerView.findViewById(R.id.refresh_list_footer_text);
		pb_footerMore = (ProgressBar)footerView.findViewById(R.id.refresh_list_footer_progressbar);
		
		brand = (Button)findViewById(R.id.drink_book_brand_button);
		price = (Button)findViewById(R.id.drink_book_price_button);
		type = (Button)findViewById(R.id.drink_book_type_button);
		popularity = (Button)findViewById(R.id.drink_book_popularity_button);
		back = (LinearLayout)findViewById(R.id.drink_book_back_button);
		cart = (LinearLayout)findViewById(R.id.drink_book_cart_button);
		brand.setOnClickListener(this);
		price.setOnClickListener(this);
		type.setOnClickListener(this);
		popularity.setOnClickListener(this);
		back.setOnClickListener(this);
		cart.setOnClickListener(this);
		
		drinksListView = (ListView)findViewById(R.id.drinks_book_listview);
		drinksListView.addFooterView(footerView);
		drinksList = new ArrayList<Drinks>();
		initData();
		drinksAdapter = new DrinksBookListAdapter(ctx, drinksList);
		drinksListView.setAdapter(drinksAdapter);
		drinksListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				if(arg2 == arg0.getAdapter().getCount()-1) {
					tv_footerMore.setText(R.string.app_list_footer_getting_text);
					pb_footerMore.setVisibility(ProgressBar.VISIBLE);
					initData();
				} else {
					Drinks drinks = (Drinks) arg0.getAdapter().getItem(arg2);
					drinks.setCurrent(true);
					ctx.getIntent().putExtra("drinks", drinks);
					ctx.setContentView(new DrinksBookDrinkInfoWidget(ctx));
				}
			}
		});
		
		drinksBookDialog = new DrinksBookDialog(ctx);
	}
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.drink_book_brand_button:
			popupWindow = drinksBookDialog.makePopupWindow(brand, Wine.BRAND, mHandler);
			popupWindow.showAsDropDown(brand, brand.getWidth()/2*-1, 0);
			break;
		case R.id.drink_book_price_button:
			popupWindow = drinksBookDialog.makePopupWindow(price, Wine.PRICE, mHandler);
			popupWindow.showAsDropDown(price, price.getWidth()/2*-1, 0);
			//drinksBookDialog.showSelectDialog(ctx, Wine.PRICE, mHandler);
			break;
		case R.id.drink_book_type_button:
			popupWindow = drinksBookDialog.makePopupWindow(type, Wine.TYPE, mHandler);
			popupWindow.showAsDropDown(type);
			break;
		case R.id.drink_book_popularity_button:
			popupWindow = drinksBookDialog.makePopupWindow(popularity, Wine.POPULARITY, mHandler);
			popupWindow.showAsDropDown(popularity);
			break;
		case R.id.drink_book_back_button:
			ctx.finish();
			break;
		case R.id.drink_book_cart_button:
			ctx.setContentView(new DrinksBookCartWidget(ctx));
			break;
		default:
			break;
		}
	}
	
	private void initData() {
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		if(wineBrand.getStrId().equals("") || wineBrand.getStrId().equals("-1")) {
			wineBrandName = "-1";
		} else {
			wineBrandName = wineBrand.getName();
		}
		if(StringUtils.isEmpty(wineType.getStrId())) {
			wineTypeId = "-1";
		} else {
			wineTypeId = wineType.getStrId();
		}
		if(winePrice.getStrId().equals("") || winePrice.getStrId().equals("-1")) {
			wineLowPrice = "-1";
			wineHighPrice = "-1";
		} else {
			String priceString = winePrice.getName();
			String[] ss = priceString.split("-");
			if(ss.length == 2) {
				wineLowPrice = StringUtils.getDigitString(ss[0]);
				wineHighPrice = StringUtils.getDigitString(ss[1]);
			} else {
				wineLowPrice = StringUtils.getDigitString(priceString);
				wineHighPrice = "90000";
			}
			
		}
		
		new Thread() {
			public void run() {
				if(reSet) {
					drinksList.clear();
				}
				mCount = drinksList.size();
				if(Global.DEBUG) {
					System.out.println("查询条件 = " + wineTypeId
							+ " : " + wineBrandName
							+ " : " + wineLowPrice
							+ " : " + wineHighPrice
							+ " : " + mCount);
				}
				String response = null;
				try {
					/*String ss = "?wineBrandId=-1&wineTypeId=-1&wineLowPrice=-1&wineHighPrice=-1&count=0";
					response = HttpUtils.doGet(url + ss);*/
					
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("wineBrandName", wineBrandName));
					params.add(new BasicNameValuePair("wineTypeId", wineTypeId));
					params.add(new BasicNameValuePair("wineLowPrice", wineLowPrice));
					params.add(new BasicNameValuePair("wineHighPrice", wineHighPrice));
					params.add(new BasicNameValuePair("count", mCount +""));
					response = HttpUtils.Post(url, params);
					
					if(Global.DEBUG) {
						System.out.println("-----------------------------\n" + response);
					}
				} /*catch (ClientProtocolException e) {
					Log.e(TAG, "ClientProtocolException", e);
				} catch (IOException e) {
					Log.e(TAG, "IOException", e);
				} */catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					Drinks drinks;
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						JSONArray jList = jManager.getJsonList();
						if(null == jList) {
							
						} else {
							for(int i=0; i< jList.length(); i++) {
								JSONObject jObject = getJSONObject(jList, i);
								if(null != jObject) {
									drinks = new Drinks();
									drinks.setId(getString(jObject, "itemid"));
									drinks.setName(getString(jObject, "title"));
									drinks.setImgURL(getString(jObject, "thumb"));
									drinks.setPriceTip(StringUtils.parseFloat(getString(jObject, "price")));
									drinks.setPriceMarket(StringUtils.parseFloat(getString(jObject, "marketprice")));
									drinks.setBrand(getString(jObject, "catname"));
									drinks.setType(getString(jObject, "catname"));
									drinks.setRatings(StringUtils.parseFloat(getString(jObject, "level")));
									drinks.setPopularity(StringUtils.parseInt(getString(jObject, "hits")));
									//drinks.setNum(1);
									for(Drinks d : drinksList) {
										if(d.getId().equals(drinks.getId())) {
											System.out.println("重复酒水 --------   " + d.getName());
											break;
										}
									}
									drinksList.add(drinks);
								}
							}
							Global.drinksList = drinksList;
						}
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}
				mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}
	private void compareDrinksList(int flag) {
		Collections.sort(drinksList, new ListComparatorManager(flag));
		drinksAdapter.notifyDataSetChanged();
	}
	
	@Override
	public void notifyAdapter() {
		
	}
}
